package de.piratech.dasding.data.database.couch;

import java.util.ArrayList;
import java.util.List;

import org.ektorp.ComplexKey;
import org.ektorp.CouchDbConnector;
import org.ektorp.support.CouchDbRepositorySupport;

import de.piratech.dasding.data.Event;
import de.piratech.dasding.data.Location;
import de.piratech.dasding.data.database.EventData;
import de.piratech.dasding.data.database.couch.adapters.EventAdapter;

public class EventDataImpl extends CouchDbRepositorySupport<EventAdapter>
		implements EventData {

	protected EventDataImpl(CouchDbConnector db) {
		super(EventAdapter.class, db, "Event");
	}

	@Override
	public Event createEvent(Event event) {
		if (event instanceof EventAdapter) {
			add((EventAdapter) event);
		}
		return event;
	}

	@Override
	public void deleteEvent(String id) {
		remove(get(id));
	}

	@Override
	public Event updateEvent(Event event) {
		if (event instanceof EventAdapter) {
			update((EventAdapter) event);
		} else {
			update(new EventAdapter(event));
		}
		return event;
	}

	@Override
	public Event getEvent(String id) {
		return get(id);
	}

	@Override
	public List<Event> getEvents() {
		return new ArrayList<Event>(getAll());
	}

	@Override
	public List<Event> getEventsByUser(String userId) {
		return new ArrayList<Event>(queryView("byUser", userId));
	}

	@Override
	public List<Event> getEventsByLocation(Location location) {
		return new ArrayList<Event>(queryView("byLocation",
				ComplexKey.of(location)));
	}
}
